package com.liuym.admin.util;

import com.liuym.admin.GradeAdminApplication;
import com.liuym.admin.repository.model.entity.TableNameEntity;
import com.liuym.admin.service.TableNameService;

import java.util.Calendar;
import java.util.Date;

/**
 * @author Liuym
 * @date 2018/12/29 14:12
 * @describe：生成表名工具类
 */
public class StudentScoreTableNameUtil {

    private static TableNameService tableNameService;

    static {
        tableNameService = GradeAdminApplication.context.getBean(TableNameService.class);
    }

    private static StringBuffer studentScoreTableName = new StringBuffer("t_student_score");


    //  private static StringBuffer studentScoreTableName = new StringBuffer("t_student_score");
    private static StringBuffer studentScoreTableNameBase = new StringBuffer();

    public static String getStudentScoreTableName(String tableName) {
        return tableNameService.findByTableAndTime("%" + tableName + "%").getTableName();
    }

    public static StringBuffer getStudentScoreTableName() {
        return studentScoreTableName;
    }
    public static void setStudentScoreTableName(StringBuffer studentScoreTableName) {
        Calendar calendar = Calendar.getInstance();
        int month = calendar.get((Calendar.MONTH)) + 1;
        int year = calendar.get(Calendar.YEAR);
        studentScoreTableNameBase.append("_" + year + "-" + String.valueOf(year + 1) + (((month >= 9 && month <= 12) || (month == 1)) ? "_2" : "_1"));
        //因为是static变量 故这里不能用 =
        StudentScoreTableNameUtil.studentScoreTableName = studentScoreTableName.append(studentScoreTableNameBase);
        TableNameEntity tableNameEntity = tableNameService.findByTableAndTime(StudentScoreTableNameUtil.studentScoreTableName.toString());
        if (tableNameEntity == null) {
            TableNameEntity tableName = new TableNameEntity();
            tableName.setCreateTime(new Date());
            tableName.setTableName(StudentScoreTableNameUtil.studentScoreTableName.toString());
            tableNameService.insert(tableName);
        }
        StudentScoreTableNameUtil.studentScoreTableNameBase = StudentScoreTableNameUtil.studentScoreTableNameBase.delete(0, studentScoreTableNameBase.length());
    }
}
